package imu.g3.controller;

import imu.g3.model.MultiFileModel;
import imu.g3.model.MyProjectUploadFiles;
import imu.g3.model.User;
import imu.g3.service.FileService;
import imu.g3.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

@RequestMapping(value = "/upload")
@Controller
public class IconUploadController {
    //得到一个用来记录日志的对象，这样在打印信息时能够标记打印的是哪个类的信息
    private static final Log logger = LogFactory.getLog(IconUploadController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;

    /**
     * 单文件上传
     */
    @RequestMapping("/fileupload")
    public String oneFileUpload(MultipartFile photo, HttpServletRequest request) {
        /**
         * 文件上传到服务器的位置“/uploadfiles”,该位置是指
         */
        String realpath = request.getSession().getServletContext().getRealPath("uploadfiles");
        String fileName = photo.getOriginalFilename();
        File targetFile = new File(realpath, fileName);

        //上传
        try {
            photo.transferTo(targetFile);

            /*//将图片名字存到数据库中
            User user = (User) request.getSession().getAttribute("User");
            String username = user.getName();
            userService.updateIconName(username,fileName);*/

        }catch (Exception e){
            e.printStackTrace();
        }
        return "my";
    }


    /**
     * 单文件上传
     */
    @RequestMapping("/iconupload")
    public String oneIconUpload(MultipartFile photo, HttpServletRequest request) {
        /**
         * 文件上传到服务器的位置“/uploadfiles”,该位置是指
         */
        String realpath = request.getSession().getServletContext().getRealPath("uploadfiles");
        String fileName = photo.getOriginalFilename();
        File targetFile = new File(realpath, fileName);
        if (!targetFile.exists())
            targetFile.mkdirs();

        //上传
        try {
            photo.transferTo(targetFile);

            //将图片名字存到数据库中
            User user = (User) request.getSession().getAttribute("User");
            String username = user.getName();
            userService.updateIconName(username,fileName);

        }catch (Exception e){
            e.printStackTrace();
        }
        return "my";
    }

    /**
     * 多文件上传
     */
    @RequestMapping("/multifile")
    public String multiFileUpload(@ModelAttribute MultiFileModel multiFileModel, HttpServletRequest request) {
        String realpath = request.getServletContext().getRealPath("uploadfiles");
        File targetDir = new File(realpath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        List<MultipartFile> files = multiFileModel.getMyFile();
        List<String> fileDiscription = multiFileModel.getDescription();
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            String fileName = file.getOriginalFilename();
            File targetFile = new File(realpath, fileName);
            String discription = fileDiscription.get(i);
            if(discription.equals("")){
                discription = fileName;
            }
            if (!targetFile.exists()){
                targetFile.mkdirs();
            }
            // 上传
            try {
                file.transferTo(targetFile);
                //上传后将：文件名称，文件描述，文件上传者保存到数据库中
                MyProjectUploadFiles myProjectUploadFiles = new MyProjectUploadFiles();
                UUID uuid = UUID.randomUUID();
                myProjectUploadFiles.setId(uuid.toString());myProjectUploadFiles.setFileName(fileName);
                myProjectUploadFiles.setFileDiscription(discription);
                User user = (User)request.getSession().getAttribute("User");
                String currentUser = user.getName().equals("")? user.getPhone():user.getName();
                myProjectUploadFiles.setFileUploadUser(currentUser);
                int res = fileService.insertFileInfo(myProjectUploadFiles);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "my";
    }

}